//
//  LZRetrievePasswordViewController.m
//  laziz_Consumer
//
//  Created by ZhaoDongBo on 2016/10/25.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZRetrievePasswordViewController.h"
#import "LZResetPasswordViewController.h"
#import "LZAreaCodeViewController.h"
#import "LZLoginTextFieldView.h"
#import "LZRetrieveTitleView.h"

#import "UIViewController+NavigationItemSetting.h"
#import "UIView+Rotation.h"
#import "NSString+LZRegex.h"

#import "Masonry.h"

#import "TShareEventHandler.h"
#import "LZRemindView.h"
#import "LZAlertView.h"
#import "LZUserInfoPresenter.h"

@interface LZRetrievePasswordViewController ()

@property (nonatomic, strong) UIImageView * bgImageView;
@property (nonatomic, strong) UIButton * nextStepButton;
@property (nonatomic, strong) LZLoginTextFieldView * textFieldView;
@property (nonatomic, strong) LZRetrieveTitleView * titleView;

@property (strong, nonatomic) UIButton *nav_left_back;
@property (assign, nonatomic) CGFloat lzAlpha;

@property (nonatomic, strong) LZUserInfoPresenter * userInfoPresenter;

@property (nonatomic, strong) NSTimer * timer;      //验证码倒计时
@property (nonatomic, assign) int count;

@end

@implementation LZRetrievePasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"找回密码页面";
    
    self.lzAlpha = 0;
    
    self.userInfoPresenter = [[LZUserInfoPresenter alloc] init];
    
    [self configViews];
    
    [self configAutoLayout];
    
    [self getVerifiCodeAction];
    
    [self configNavigationBar];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)fd_prefersNavigationBarHidden {
    return YES;
}

#pragma mark - Private method

- (void)configNavigationBar {
    
    self.nav_left_back = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nav_left_back.frame = CGRectMake(0, 0, 60, 40);
    [self.nav_left_back addTarget:self action:@selector(navbarBackButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *image_back = [UIImage imageNamed:@"lz_back"];
    [self.nav_left_back setImage:image_back forState:UIControlStateNormal];
    self.nav_left_back.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, CGRectGetWidth(self.nav_left_back.bounds)-image_back.size.width);
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        [self.nav_left_back setLanguageRotaion];
    }
    
    [self hiddenBarNavigationItemSetting:@[self.nav_left_back] type:NAVIGATIONITEMSETTING_LEFT];
    
    [self lz_setCustomBarAlpha:self.lzAlpha];
    
}

- (void)configViews {
    
    [self.view addSubview:self.bgImageView];
    [self.view addSubview:self.titleView];
    [self.view addSubview:self.textFieldView];
    [self.view addSubview:self.nextStepButton];
}

- (void)configAutoLayout {
    
    GET_SCREEN_SCALE(scale);
    
    [self.titleView makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(107*scale);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(160*scale);
    }];
    
    [self.textFieldView makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.view.centerY);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(110.0*scale);
    }];
    
    [self.nextStepButton makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(55.0);
    }];
}

- (void)getVerifiCodeAction {
    
    WS(weakSelf);
    [self.timer invalidate];
    self.textFieldView.buttonAction_TF_Block = ^(LZLOGIN_TF_BUTTON_TAG buttonTag) {
        
        if (buttonTag == LZLOGIN_TF_BUTTON_TAG_VERIFICCODE) {
            DLog(@"获取验证码");
            [weakSelf validateUserName];
        }
    };
}

- (void)startTimer {
    self.textFieldView.countdownLabel.text = @"60s";
    [self.timer invalidate];
    self.count = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(updateTime)
                                                userInfo:nil
                                                 repeats:YES];
    self.textFieldView.countdownLabel.hidden = NO;
    self.textFieldView.verificCodeButton.hidden = YES;
}

- (void)stopTimer {
    [self.timer invalidate];
    self.textFieldView.countdownLabel.hidden = YES;
    self.textFieldView.verificCodeButton.hidden = NO;
}

- (void)updateTime
{
    self.count ++;
    if (self.count >= 60)
    {
        [self stopTimer];
        return;
    }
    
    self.textFieldView.countdownLabel.text = [NSString stringWithFormat:@"%is", 60-self.count];
    
    if (self.count == 60) {
        self.textFieldView.countdownLabel.hidden = YES;
        self.textFieldView.verificCodeButton.hidden = NO;
    }
}

#pragma mark - event

- (void)navbarBackButtonClickAction:(UIButton*)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)buttonAction:(UIButton *)sender {
    
    if (self.type == FindPasswordType_Phone) {
        [self requestValidateForgetMobilePassword];
    }
    else if (self.type == FindPasswordType_Mail) {
        [self requestValidateForgetMailPassword];
    }
}

// 请求  校验忘记手机号密码  接口
- (void)requestValidateForgetMobilePassword {
    
    NSString *userName = [NSString stringWithFormat:@"%@%@",
                self.textFieldView.areaCodeTextField.text,
                self.textFieldView.mobileNumTextField.text];
    NSString *verifiCode = self.textFieldView.verificCodeTextField.text;
    
    if (self.textFieldView.mobileNumTextField.text.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                         andContent:LZLocalizedString(@"login_enter_mobile", @"")];
        return;
    }
    
//    else if (userName.length < 11) {
//        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
//                         andContent:LZLocalizedString(@"enter_invalid_mobile", @"")];
//        return;
//    }
    
    else if (verifiCode.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                         andContent:LZLocalizedString(@"login_enter_verifi_code", @"")];
        return;
    } 
    
    WS(weakSelf);
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];

    [self.userInfoPresenter userForgetMobilePasswordWith:userName andVerifiCode:verifiCode onSuccess:^(id data) {
        DLog(@"忘记密码 --- 忘记密码校验:%@", data);
        
        [weakSelf stopLoadingViewForView:weakSelf.view];

        [weakSelf stopTimer];
        
        LZResetPasswordViewController * vc = [[LZResetPasswordViewController alloc] init];
        vc.userName = userName;
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
    } onFail:^(NSString *fail) {
        DLog(@"error: %@", fail);

        [weakSelf stopLoadingViewForView:weakSelf.view];

        if ([fail isEqualToString:@"0400001"] || [fail isEqualToString:@"0100010"] || [fail isEqualToString:@"0500001"]) { //0100010 验证码错误！
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"enter_invalid_verifi", nil)];
        }
        else if ([fail isEqualToString:@"0500031"]) { //0500031 该用户已被停用，请联系管理员
            LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"mag_account_stopstate", nil)
                                                             andImage:nil
                                                    cancelButtonTitle:LZLocalizedString(@"cancel", nil)
                                                    otherButtonTitles:nil, nil];
            [alert show];
        }
        else {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"register_failed", nil)];
        }
    }];
}

// 请求  校验忘记邮箱密码  接口
- (void)requestValidateForgetMailPassword {
    
    NSString *userName = self.textFieldView.mobileNumTextField.text;
    NSString *verifiCode = self.textFieldView.verificCodeTextField.text;
    
    if (userName.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                         andContent:LZLocalizedString(@"login_enter_email", nil)];
        return;
    }
    else if (verifiCode.length <= 0) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                         andContent:LZLocalizedString(@"login_enter_verifi_code", @"")];
        return;
    }
    else if (![userName isEmailAddress]) {
        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                         andContent:LZLocalizedString(@"invalid_email_remind", nil)];
        return;
    }
    
    WS(weakSelf);
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];

    [self.userInfoPresenter userForgetMailPasswordWith:userName andVerifiCode:verifiCode onSuccess:^(id data) {
        DLog(@"忘记密码 --- 忘记密码校验:%@", data);
        
        [weakSelf stopLoadingViewForView:weakSelf.view];

        [weakSelf stopTimer];
        
        LZResetPasswordViewController * vc = [[LZResetPasswordViewController alloc] init];
        vc.userName = userName;
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
    } onFail:^(NSString *fail) {
        DLog(@"error: %@", fail);
        
        [weakSelf stopLoadingViewForView:weakSelf.view];

        if ([fail isEqualToString:@"0400001"] || [fail isEqualToString:@"0100010"] || [fail isEqualToString:@"0500001"]) { //0100010 验证码错误！
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"enter_invalid_verifi", nil)];
        }
        else if ([fail isEqualToString:@"0500031"]) { //0500031 该用户已被停用，请联系管理员
            LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"mag_account_stopstate", nil)
                                                             andImage:nil
                                                    cancelButtonTitle:LZLocalizedString(@"cancel", nil)
                                                    otherButtonTitles:nil, nil];
            [alert show];
        }
        else {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"register_failed", nil)];
        }
    }];
}

//验证用户是否存在（包括手机号，邮箱，用户名）---不存在则返回"statusCode":"2000000"
- (void)validateUserName {
    
    NSString * userName = nil;
    
    if (self.type == FindPasswordType_Phone) {
        userName = [NSString stringWithFormat:@"%@%@",
                    self.textFieldView.areaCodeTextField.text,
                    self.textFieldView.mobileNumTextField.text];
        
        if (self.textFieldView.mobileNumTextField.text.length <= 0) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"login_enter_mobile", @"")];
            return;
        }
        
//        if (userName.length < 11) {
//            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
//                             andContent:LZLocalizedString(@"enter_invalid_mobile", @"")];
//            return;
//        }
    }
    else if (self.type == FindPasswordType_Mail) {
        userName = self.textFieldView.mobileNumTextField.text;
        if (userName.length <= 0) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"login_enter_email", nil)];
        }
        else if (![userName isEmailAddress]) {
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"invalid_email_remind", nil)];
            return;
        }
    }

    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    WS(weakSelf);
    [self.userInfoPresenter userValidateUserNameWith:userName onSuccess:^(id data) {
        
        if ([[data objectForKey:@"statusCode"] integerValue] == kCodeSuccesss) {
            
            [weakSelf stopLoadingViewForView:weakSelf.view];
            // 不存在
            if (self.type == FindPasswordType_Phone) {
                // 手机号码不存在
                LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"find_password_mobile_inexistence_remind", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
                [alert show];
            }
            else if (self.type == FindPasswordType_Mail) {
                // 邮箱不存在
                LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"find_password_email_inexistence_remind", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
                [alert show];
            }
        } else {
            // 存在
            [weakSelf requestSendValidateCodeWithUserName:userName];
        }
    } onFail:^(NSString *fail) {
        DLog(@"error: %@", fail);
        
        [weakSelf stopLoadingViewForView:weakSelf.view];
        
        [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                         andContent:fail];
    }];
}

// 发送验证码
- (void)requestSendValidateCodeWithUserName:(NSString *)userName  {

    WS(weakSelf)
    
    [self.userInfoPresenter userGetVerificationCodeType:@"3" andPhoneNum:userName onSuccess:^(id data) {
        DLog(@"身份验证 -（3）- 获取验证码:%@", data);
        [weakSelf stopLoadingViewForView:weakSelf.view];
        //显示倒计时
        [weakSelf startTimer];
        
    } onFail:^(NSString *fail) {
        DLog(@"error: %@", fail);
        [weakSelf stopLoadingViewForView:weakSelf.view];

        if ([fail isEqualToString:@"9999999"]) {
            
//            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
//                             andContent:LZLocalizedString(@"send_code_maxnum_remind", nil)];
            LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"send_code_maxnum_remind", nil)
                                                             andImage:[UIImage imageNamed:@"error_image"]
                                                    cancelButtonTitle:LZLocalizedString(@"confirm", nil)
                                                    otherButtonTitles:nil, nil];
            [alert show];
        }
        else {
            
            [LZRemindView initWithImage:[UIImage imageNamed:@"error_image"]
                             andContent:LZLocalizedString(@"vificode_failed", nil)];
        }

    }];
}

#pragma mark - Setter/Getter

- (UIImageView *)bgImageView {
    
    if (_bgImageView == nil) {
        _bgImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
        _bgImageView.image = [UIImage imageNamed:@"lz_bg"];
    }
    
    return _bgImageView;
}

- (UIButton *)nextStepButton {
    
    if (_nextStepButton == nil) {
        _nextStepButton = [[UIButton alloc] init];
        _nextStepButton.backgroundColor = UIColorFromRGB(0xf2871c, 1);
        GET_SCREEN_SCALE(scale);
        _nextStepButton.titleLabel.font = [UIFont systemFontOfSize:17.0*scale];
        [_nextStepButton setTitle:LZLocalizedString(@"next_set_password", @"") forState:UIControlStateNormal];
        [_nextStepButton setTitleColor:UIColorFromRGB(0xffffff, 1) forState:UIControlStateNormal];
        [_nextStepButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _nextStepButton;
}

- (LZLoginTextFieldView *)textFieldView {
    
    if (_textFieldView == nil) {
        if (self.type == FindPasswordType_Phone) {
            _textFieldView = [[LZLoginTextFieldView alloc] initWithPage:LZLOGIN_TF_TYPE_PAGE_FINDPASSWORD_PHONE];
        }
        else if (self.type == FindPasswordType_Mail) {
            _textFieldView = [[LZLoginTextFieldView alloc] initWithPage:LZLOGIN_TF_TYPE_PAGE_FINDPASSWORD_MAIL];
        }
        
        WS(weakSelf);
        _textFieldView.clickAreaCodeTextFieldBlock = ^(UILabel *label) {
            LZAreaCodeViewController *vc = [[LZAreaCodeViewController alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
            vc.SelectedAreaCodeBlock = ^(NSString *areaCode) {
                label.text = areaCode;
            };
        };
    }    
    
    return _textFieldView;
}

- (LZRetrieveTitleView *)titleView {
    
    if (_titleView == nil) {
        _titleView = [[LZRetrieveTitleView alloc] initWithPage:LZRETRIEVE_TITLE_PAGE_RETRIEVE];
        if (self.type == FindPasswordType_Phone) {
            _titleView.subTitleText = [LZLocalizedString(@"find_password_mobile_remind", nil) copy];
        }
        else if (self.type == FindPasswordType_Mail) {
            _titleView.subTitleText = [LZLocalizedString(@"find_password_email_remind", nil) copy];
        }
    }
    
    return _titleView;
}

@end
